package com.liuyi.netty.im.lychat.im;

import cn.hutool.core.util.EnumUtil;
import com.github.pagehelper.PageHelper;
import com.liuyi.netty.im.commons.codes.CodeConst;
import com.liuyi.netty.im.commons.codes.data.event.Message;
import com.liuyi.netty.im.commons.codes.data.event.Session;
import com.liuyi.netty.im.commons.codes.data.event.message.playload.Playload;
import com.liuyi.netty.im.lychat.modular.entity.ChatSession;
import com.liuyi.netty.im.lychat.modular.enums.SessionType;
import com.liuyi.netty.im.lychat.modular.service.IChatSessionService;
import com.liuyi.netty.im.server.handle.service.SessionService;
import com.liuyi.netty.im.server.util.ImHelp;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Comparator;
import java.util.List;

/**
 * 会话 实现
 *
 * @author Mr.Fmy
 * @since 2021/12/25
 */
@Service
public class LychatSessionService implements SessionService {

    @Resource
    private IChatSessionService chatSessionService;

    @Override
    public List<Session> listByUserId(String userId) {
        PageHelper.startPage(1, 100, false);
        List<ChatSession> chatSessions = chatSessionService.listByUserId(userId);
        List<Session> sessions = chatSessionService.wrapperSession(chatSessions);
        Comparator<Session> reversed = Comparator.<Session>comparingLong(i -> {
            if (i.getLastMessage() instanceof Message) {
                return ((Message<?>) i.getLastMessage()).getCreateTime();
            }
            return -1L;
        }).reversed();
        sessions.sort(reversed);
        return sessions;
    }

    @Override
    public Session getByUserAndSessionId(String userId, String sessionId) {
        return chatSessionService.wrapperSession(chatSessionService.cache().getByUserIdAndSessionId(userId, sessionId));
    }

    @Override
    public Session setLastMessage(String userId, String sessionId, Message<? extends Playload> message) {
        ChatSession chatSession = chatSessionService.cache().getByUserIdAndSessionId(userId, sessionId);
        if (chatSession == null) {
            String toId = ImHelp.sessionIdToId(sessionId);
            CodeConst.SessionType sessionType = ImHelp.sessionIdToType(sessionId);
            chatSession = chatSessionService.createSession(userId, toId, EnumUtil.fromString(SessionType.class, sessionType.name()));
        }
        CodeConst.MsgType msgType = message.getMsgType();
        if (!userId.equals(message.getFromId()) && !msgType.equals(CodeConst.MsgType.GROUP_SYS)
                && !msgType.equals(CodeConst.MsgType.GROUP_HINT)) {
            //不是发送人+不是群系统消息+不是群提醒消息（以上条件都不满足就记录未读数）
            chatSessionService.cache().incrUnreadCount(userId, sessionId);
        }
        chatSessionService.cache().updadteLastMessage(userId, sessionId, message);
        return chatSessionService.wrapperSession(chatSession);
    }
}
